package com.example.monitoring.controller;

import com.example.monitoring.config.MonitoringProperties;
import com.example.monitoring.service.ConfigurationFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

/**
 * 配置管理控制器类
 * 
 * @author rsz
 * @since 2024-04-13
 */
@Slf4j
@Controller
@RequestMapping("/config")
public class ConfigController {

    private final MonitoringProperties monitoringProperties;
    private final ConfigurationFileService configurationFileService;

    @Autowired
    public ConfigController(MonitoringProperties monitoringProperties, ConfigurationFileService configurationFileService) {
        this.monitoringProperties = monitoringProperties;
        this.configurationFileService = configurationFileService;
    }
    
    @PostConstruct
    public void init() {
        // 应用启动时加载配置文件
        log.info("初始化配置，尝试从文件加载");
        MonitoringProperties loadedProperties = configurationFileService.loadConfiguration();
        
        if (loadedProperties != null) {
            // 如果成功加载，则更新当前配置
            updatePropertiesFromLoaded(loadedProperties);
            log.info("已从文件加载配置");
        } else {
            // 如果加载失败，则保存当前配置到文件
            configurationFileService.saveConfiguration(monitoringProperties);
            log.info("无法从文件加载配置，已保存当前配置到文件");
        }
        
        // 确保targetService始终是一个有效的列表
        ensureTargetServiceList();
    }
    
    /**
     * 确保targetService始终是一个有效的列表
     */
    private void ensureTargetServiceList() {
        if (monitoringProperties.getTargetService() == null) {
            monitoringProperties.setTargetService(new ArrayList<>());
            log.info("初始化空的目标服务列表");
        }
    }
    
    /**
     * 从加载的配置更新当前配置
     */
    private void updatePropertiesFromLoaded(MonitoringProperties loaded) {
        // 保留原始filePath设置
        String originalFilePath = monitoringProperties.getConfig().getFilePath();
        
        // 更新配置
        // 确保targetService是有效的列表
        if (loaded.getTargetService() == null) {
            loaded.setTargetService(new ArrayList<>());
        }
        monitoringProperties.setTargetService(loaded.getTargetService());
        monitoringProperties.setNetworkCheck(loaded.getNetworkCheck());
        monitoringProperties.setMiddleware(loaded.getMiddleware());
        monitoringProperties.setReport(loaded.getReport());
        
        // 加载后确保中间件配置完整初始化
        ensureMiddlewareInitialized();
        
        // 恢复原始filePath设置
        if (loaded.getConfig() == null) {
            loaded.setConfig(new MonitoringProperties.Config());
        }
        loaded.getConfig().setFilePath(originalFilePath);
        monitoringProperties.setConfig(loaded.getConfig());
    }

    /**
     * 配置管理页面
     */
    @GetMapping
    public String configPage(Model model) {
        log.debug("访问配置管理页面");
        model.addAttribute("pageTitle", "配置管理");
        model.addAttribute("configFilePath", configurationFileService.getConfigFilePath());
        return "config";
    }

    /**
     * 获取当前配置
     */
    @GetMapping("/api/current")
    @ResponseBody
    public ResponseEntity<MonitoringProperties> getCurrentConfig() {
        log.debug("获取当前配置");
        // 确保targetService是有效的列表
        ensureTargetServiceList();
        return ResponseEntity.ok(monitoringProperties);
    }

    /**
     * 获取所有目标服务配置
     */
    @GetMapping("/api/target-services")
    @ResponseBody
    public ResponseEntity<List<MonitoringProperties.TargetService>> getTargetServices() {
        log.debug("获取所有目标服务配置");
        ensureTargetServiceList();
        return ResponseEntity.ok(monitoringProperties.getTargetService());
    }

    /**
     * 添加或更新目标服务配置
     */
    @PostMapping("/api/target-service")
    @ResponseBody
    public ResponseEntity<MonitoringProperties.TargetService> addOrUpdateTargetService(
            @RequestBody MonitoringProperties.TargetService targetService) {
        log.debug("添加或更新目标服务配置: {}", targetService);
        
        // 确保targetService列表已初始化
        ensureTargetServiceList();
        
        // 检查是否已存在相同名称的服务
        boolean updated = false;
        if (targetService.getName() == null || targetService.getName().trim().isEmpty()) {
            return ResponseEntity.badRequest().build();
        }
        
        for (int i = 0; i < monitoringProperties.getTargetService().size(); i++) {
            MonitoringProperties.TargetService existingService = monitoringProperties.getTargetService().get(i);
            if (existingService != null && 
                existingService.getName() != null && 
                existingService.getName().equals(targetService.getName())) {
                monitoringProperties.getTargetService().set(i, targetService);
                updated = true;
                log.info("更新已存在的目标服务: {}", targetService.getName());
                break;
            }
        }
        
        // 如果不存在，则添加新服务
        if (!updated) {
            monitoringProperties.getTargetService().add(targetService);
            log.info("添加新的目标服务: {}", targetService.getName());
        }
        
        // 保存到配置文件
        boolean saved = configurationFileService.saveConfiguration(monitoringProperties);
        if (!saved) {
            log.error("保存配置文件失败");
            return ResponseEntity.internalServerError().build();
        }
        
        return ResponseEntity.ok(targetService);
    }
    
    /**
     * 删除目标服务配置
     */
    @DeleteMapping("/api/target-service/{index}")
    @ResponseBody
    public ResponseEntity<Void> deleteTargetService(@PathVariable int index) {
        log.debug("删除目标服务配置, 索引: {}", index);
        
        // 确保targetService列表已初始化
        ensureTargetServiceList();
        
        if (index >= 0 && index < monitoringProperties.getTargetService().size()) {
            String serviceName = monitoringProperties.getTargetService().get(index).getName();
            monitoringProperties.getTargetService().remove(index);
            log.info("已删除目标服务: {}", serviceName);
            
            // 保存到配置文件
            boolean saved = configurationFileService.saveConfiguration(monitoringProperties);
            if (!saved) {
                log.error("保存配置文件失败");
                return ResponseEntity.internalServerError().build();
            }
            
            return ResponseEntity.ok().build();
        }
        return ResponseEntity.badRequest().build();
    }

    /**
     * 添加或更新网络服务检测配置
     */
    @PostMapping("/api/network-service")
    @ResponseBody
    public ResponseEntity<MonitoringProperties.NetworkCheck.Service> addOrUpdateNetworkService(
            @RequestBody NetworkServiceRequest request) {
        log.info("=== 网络服务请求开始 ===");
        log.info("完整请求对象: {}", request);
        log.info("是否编辑模式: {}", request.isEditing());
        log.info("编辑服务索引: {}", request.getEditingServiceIndex());
        log.info("分组索引: {}", request.getGroupIndex());
        log.info("服务信息: {}", request.getService());
        
        MonitoringProperties.NetworkCheck.Service service = request.getService();
        Integer groupIndex = request.getGroupIndex();
        boolean isEditing = request.isEditing();
        Integer editingServiceIndex = request.getEditingServiceIndex();
        
        // 确保networkCheck已初始化
        if (monitoringProperties.getNetworkCheck() == null) {
            monitoringProperties.setNetworkCheck(new MonitoringProperties.NetworkCheck());
        }
        
        if (groupIndex != null && groupIndex >= 0) {
            // 分组模式
            if (monitoringProperties.getNetworkCheck().getGroups() == null) {
                monitoringProperties.getNetworkCheck().setGroups(new ArrayList<>());
            }
            
            if (groupIndex < monitoringProperties.getNetworkCheck().getGroups().size()) {
                MonitoringProperties.NetworkCheck.ServiceGroup group = monitoringProperties.getNetworkCheck().getGroups().get(groupIndex);
                if (group.getServices() == null) {
                    group.setServices(new ArrayList<>());
                }
                
                if (isEditing && editingServiceIndex != null && editingServiceIndex >= 0 && 
                    editingServiceIndex < group.getServices().size()) {
                    // 编辑分组中的服务
                    group.getServices().set(editingServiceIndex, service);
                    log.info("更新分组 {} 中的网络监控服务: {}", group.getName(), service.getName());
                } else {
                    // 添加新服务到分组
                    group.getServices().add(service);
                    log.info("添加网络监控服务到分组 {}: {}", group.getName(), service.getName());
                }
            } else {
                return ResponseEntity.badRequest().build();
            }
        } else {
            // 传统services列表模式
            if (monitoringProperties.getNetworkCheck().getServices() == null) {
                monitoringProperties.getNetworkCheck().setServices(new ArrayList<>());
            }
            
            List<MonitoringProperties.NetworkCheck.Service> services = monitoringProperties.getNetworkCheck().getServices();
            
            if (isEditing && editingServiceIndex != null && editingServiceIndex >= 0 && 
                editingServiceIndex < services.size()) {
                // 编辑传统列表中的服务
                services.set(editingServiceIndex, service);
                log.info("更新传统列表中的网络监控服务: {}", service.getName());
            } else {
                // 检查是否是按名称更新已有服务（向后兼容）
                boolean updated = false;
                if (service.getName() != null && !service.getName().trim().isEmpty()) {
                    for (int i = 0; i < services.size(); i++) {
                        if (services.get(i).getName().equals(service.getName())) {
                            // 更新已存在的服务
                            services.set(i, service);
                            updated = true;
                            log.info("按名称更新已存在的网络监控服务: {}", service.getName());
                            break;
                        }
                    }
                }
                
                // 如果不是更新，则添加新服务
                if (!updated) {
                    services.add(service);
                    log.info("添加新的网络监控服务: {}", service.getName());
                }
            }
        }
        
        // 保存到配置文件
        boolean saved = configurationFileService.saveConfiguration(monitoringProperties);
        if (!saved) {
            log.error("保存配置文件失败");
            return ResponseEntity.internalServerError().build();
        }
        
        return ResponseEntity.ok(service);
    }

    /**
     * 网络服务请求对象
     */
    public static class NetworkServiceRequest {
        private MonitoringProperties.NetworkCheck.Service service;
        private Integer groupIndex;
        private boolean isEditing; // 是否为编辑操作
        private Integer editingServiceIndex; // 编辑的服务索引
        
        public MonitoringProperties.NetworkCheck.Service getService() {
            return service;
        }
        
        public void setService(MonitoringProperties.NetworkCheck.Service service) {
            this.service = service;
        }
        
        public Integer getGroupIndex() {
            return groupIndex;
        }
        
        public void setGroupIndex(Integer groupIndex) {
            this.groupIndex = groupIndex;
        }
        
        public boolean isEditing() {
            return isEditing;
        }
        
        public void setEditing(boolean editing) {
            isEditing = editing;
        }
        
        public Integer getEditingServiceIndex() {
            return editingServiceIndex;
        }
        
        public void setEditingServiceIndex(Integer editingServiceIndex) {
            this.editingServiceIndex = editingServiceIndex;
        }
        
        @Override
        public String toString() {
            return "NetworkServiceRequest{" +
                    "service=" + service +
                    ", groupIndex=" + groupIndex +
                    ", isEditing=" + isEditing +
                    ", editingServiceIndex=" + editingServiceIndex +
                    '}';
        }
    }

    /**
     * 删除网络服务检测配置
     */
    @DeleteMapping("/api/network-service/{index}")
    @ResponseBody
    public ResponseEntity<Void> deleteNetworkService(@PathVariable int index) {
        log.debug("删除网络服务检测配置, 索引: {}", index);
        
        // 确保networkCheck的services列表已初始化
        if (monitoringProperties.getNetworkCheck() == null || 
            monitoringProperties.getNetworkCheck().getServices() == null) {
            return ResponseEntity.badRequest().build();
        }
        
        if (index >= 0 && index < monitoringProperties.getNetworkCheck().getServices().size()) {
            monitoringProperties.getNetworkCheck().getServices().remove(index);
            
            // 保存到配置文件
            boolean saved = configurationFileService.saveConfiguration(monitoringProperties);
            if (!saved) {
                log.error("保存配置文件失败");
                return ResponseEntity.internalServerError().build();
            }
            
            return ResponseEntity.ok().build();
        }
        return ResponseEntity.badRequest().build();
    }

    /**
     * 更新JVM配置
     */
    @PostMapping("/api/middleware/jvm")
    @ResponseBody
    public ResponseEntity<MonitoringProperties.Middleware.Jvm> updateJvmConfig(
            @RequestBody MonitoringProperties.Middleware.Jvm jvm) {
        log.debug("更新JVM配置: {}", jvm);
        
        // 确保middleware对象已初始化
        ensureMiddlewareInitialized();
        
        monitoringProperties.getMiddleware().setJvm(jvm);
        
        // 保存到配置文件
        boolean saved = configurationFileService.saveConfiguration(monitoringProperties);
        if (!saved) {
            log.error("保存配置文件失败");
            return ResponseEntity.internalServerError().build();
        }
        
        return ResponseEntity.ok(monitoringProperties.getMiddleware().getJvm());
    }

    /**
     * 更新Redis配置
     */
    @PostMapping("/api/middleware/redis")
    @ResponseBody
    public ResponseEntity<MonitoringProperties.Middleware.Redis> updateRedisConfig(
            @RequestBody MonitoringProperties.Middleware.Redis redis) {
        log.debug("更新Redis配置: {}", redis);
        
        // 确保middleware对象已初始化
        ensureMiddlewareInitialized();
        
        monitoringProperties.getMiddleware().setRedis(redis);
        
        // 保存到配置文件
        boolean saved = configurationFileService.saveConfiguration(monitoringProperties);
        if (!saved) {
            log.error("保存配置文件失败");
            return ResponseEntity.internalServerError().build();
        }
        
        return ResponseEntity.ok(monitoringProperties.getMiddleware().getRedis());
    }

    /**
     * 更新Elasticsearch配置
     */
    @PostMapping("/api/middleware/elasticsearch")
    @ResponseBody
    public ResponseEntity<MonitoringProperties.Middleware.Elasticsearch> updateElasticsearchConfig(
            @RequestBody MonitoringProperties.Middleware.Elasticsearch elasticsearch) {
        log.debug("更新Elasticsearch配置: {}", elasticsearch);
        
        // 确保middleware对象已初始化
        ensureMiddlewareInitialized();
        
        monitoringProperties.getMiddleware().setElasticsearch(elasticsearch);
        
        // 保存到配置文件
        boolean saved = configurationFileService.saveConfiguration(monitoringProperties);
        if (!saved) {
            log.error("保存配置文件失败");
            return ResponseEntity.internalServerError().build();
        }
        
        return ResponseEntity.ok(monitoringProperties.getMiddleware().getElasticsearch());
    }

    /**
     * 更新MySQL配置
     */
    @PostMapping("/api/middleware/mysql")
    @ResponseBody
    public ResponseEntity<MonitoringProperties.Middleware.MySQL> updateMySQLConfig(
            @RequestBody MonitoringProperties.Middleware.MySQL mysql) {
        log.debug("更新MySQL配置: {}", mysql);
        
        // 确保middleware对象已初始化
        ensureMiddlewareInitialized();
        
        monitoringProperties.getMiddleware().setMysql(mysql);
        
        // 保存到配置文件
        boolean saved = configurationFileService.saveConfiguration(monitoringProperties);
        if (!saved) {
            log.error("保存配置文件失败");
            return ResponseEntity.internalServerError().build();
        }
        
        return ResponseEntity.ok(monitoringProperties.getMiddleware().getMysql());
    }

    /**
     * 更新MinIO配置
     */
    @PostMapping("/api/middleware/minio")
    @ResponseBody
    public ResponseEntity<MonitoringProperties.Middleware.MinIO> updateMinIOConfig(
            @RequestBody MonitoringProperties.Middleware.MinIO minio) {
        log.debug("更新MinIO配置: {}", minio);
        
        // 确保middleware对象已初始化
        ensureMiddlewareInitialized();
        
        monitoringProperties.getMiddleware().setMinio(minio);
        
        // 保存到配置文件
        boolean saved = configurationFileService.saveConfiguration(monitoringProperties);
        if (!saved) {
            log.error("保存配置文件失败");
            return ResponseEntity.internalServerError().build();
        }
        
        return ResponseEntity.ok(monitoringProperties.getMiddleware().getMinio());
    }
    
    /**
     * 确保middleware对象已初始化
     */
    private void ensureMiddlewareInitialized() {
        if (monitoringProperties.getMiddleware() == null) {
            monitoringProperties.setMiddleware(new MonitoringProperties.Middleware());
        }
        
        // 确保所有中间件配置对象都已初始化
        if (monitoringProperties.getMiddleware().getJvm() == null) {
            monitoringProperties.getMiddleware().setJvm(new MonitoringProperties.Middleware.Jvm());
        }
        if (monitoringProperties.getMiddleware().getRedis() == null) {
            monitoringProperties.getMiddleware().setRedis(new MonitoringProperties.Middleware.Redis());
        }
        if (monitoringProperties.getMiddleware().getElasticsearch() == null) {
            monitoringProperties.getMiddleware().setElasticsearch(new MonitoringProperties.Middleware.Elasticsearch());
        }
        if (monitoringProperties.getMiddleware().getMysql() == null) {
            monitoringProperties.getMiddleware().setMysql(new MonitoringProperties.Middleware.MySQL());
        }
        if (monitoringProperties.getMiddleware().getMinio() == null) {
            monitoringProperties.getMiddleware().setMinio(new MonitoringProperties.Middleware.MinIO());
        }
    }

    /**
     * 添加网络服务检测配置 (向后兼容，已废弃)
     * @deprecated 请使用 addOrUpdateNetworkService 方法
     */
    @Deprecated
    @PostMapping("/api/network-service-add")
    @ResponseBody
    public ResponseEntity<MonitoringProperties.NetworkCheck.Service> addNetworkService(
            @RequestBody MonitoringProperties.NetworkCheck.Service service) {
        log.debug("添加网络服务检测配置 (向后兼容): {}", service);
        NetworkServiceRequest request = new NetworkServiceRequest();
        request.setService(service);
        request.setGroupIndex(null);
        return addOrUpdateNetworkService(request);
    }

    /**
     * 添加或更新网络服务分组
     */
    @PostMapping("/api/network-group")
    @ResponseBody
    public ResponseEntity<MonitoringProperties.NetworkCheck.ServiceGroup> addOrUpdateNetworkGroup(
            @RequestBody MonitoringProperties.NetworkCheck.ServiceGroup group) {
        log.debug("添加或更新网络服务分组: {}", group);
        
        // 确保networkCheck已初始化
        if (monitoringProperties.getNetworkCheck() == null) {
            monitoringProperties.setNetworkCheck(new MonitoringProperties.NetworkCheck());
        }
        
        // 确保groups列表已初始化
        if (monitoringProperties.getNetworkCheck().getGroups() == null) {
            monitoringProperties.getNetworkCheck().setGroups(new ArrayList<>());
        }
        
        // 添加分组
        monitoringProperties.getNetworkCheck().getGroups().add(group);
        
        // 保存到配置文件
        boolean saved = configurationFileService.saveConfiguration(monitoringProperties);
        if (!saved) {
            log.error("保存配置文件失败");
            return ResponseEntity.internalServerError().build();
        }
        
        return ResponseEntity.ok(group);
    }

    /**
     * 删除网络服务分组
     */
    @DeleteMapping("/api/network-group/{index}")
    @ResponseBody
    public ResponseEntity<Void> deleteNetworkGroup(@PathVariable int index) {
        log.debug("删除网络服务分组, 索引: {}", index);
        
        // 确保networkCheck的groups列表已初始化
        if (monitoringProperties.getNetworkCheck() == null || 
            monitoringProperties.getNetworkCheck().getGroups() == null) {
            return ResponseEntity.badRequest().build();
        }
        
        if (index >= 0 && index < monitoringProperties.getNetworkCheck().getGroups().size()) {
            monitoringProperties.getNetworkCheck().getGroups().remove(index);
            
            // 保存到配置文件
            boolean saved = configurationFileService.saveConfiguration(monitoringProperties);
            if (!saved) {
                log.error("保存配置文件失败");
                return ResponseEntity.internalServerError().build();
            }
            
            return ResponseEntity.ok().build();
        }
        return ResponseEntity.badRequest().build();
    }

    /**
     * 删除分组中的网络服务
     */
    @DeleteMapping("/api/network-service/{groupIndex}/{serviceIndex}")
    @ResponseBody
    public ResponseEntity<Void> deleteNetworkServiceFromGroup(@PathVariable int groupIndex, @PathVariable int serviceIndex) {
        log.debug("删除分组中的网络服务, 分组索引: {}, 服务索引: {}", groupIndex, serviceIndex);
        
        // 确保networkCheck的groups列表已初始化
        if (monitoringProperties.getNetworkCheck() == null || 
            monitoringProperties.getNetworkCheck().getGroups() == null) {
            return ResponseEntity.badRequest().build();
        }
        
        if (groupIndex >= 0 && groupIndex < monitoringProperties.getNetworkCheck().getGroups().size()) {
            MonitoringProperties.NetworkCheck.ServiceGroup group = monitoringProperties.getNetworkCheck().getGroups().get(groupIndex);
            if (group.getServices() != null && serviceIndex >= 0 && serviceIndex < group.getServices().size()) {
                group.getServices().remove(serviceIndex);
                
                // 保存到配置文件
                boolean saved = configurationFileService.saveConfiguration(monitoringProperties);
                if (!saved) {
                    log.error("保存配置文件失败");
                    return ResponseEntity.internalServerError().build();
                }
                
                return ResponseEntity.ok().build();
            }
        }
        return ResponseEntity.badRequest().build();
    }

    /**
     * 专门用于编辑网络服务的PUT接口
     */
    @PutMapping("/api/network-service/{groupIndex}/{serviceIndex}")
    @ResponseBody
    public ResponseEntity<MonitoringProperties.NetworkCheck.Service> updateNetworkService(
            @PathVariable Integer groupIndex,
            @PathVariable Integer serviceIndex,
            @RequestBody MonitoringProperties.NetworkCheck.Service service) {
        log.info("=== 专用编辑接口 ===");
        log.info("分组索引: {}, 服务索引: {}", groupIndex, serviceIndex);
        log.info("更新的服务: {}", service);
        
        // 确保networkCheck已初始化
        if (monitoringProperties.getNetworkCheck() == null) {
            monitoringProperties.setNetworkCheck(new MonitoringProperties.NetworkCheck());
        }
        
        if (groupIndex >= 0) {
            // 分组模式
            if (monitoringProperties.getNetworkCheck().getGroups() == null || 
                groupIndex >= monitoringProperties.getNetworkCheck().getGroups().size()) {
                return ResponseEntity.badRequest().build();
            }
            
            MonitoringProperties.NetworkCheck.ServiceGroup group = monitoringProperties.getNetworkCheck().getGroups().get(groupIndex);
            if (group.getServices() == null || serviceIndex >= group.getServices().size()) {
                return ResponseEntity.badRequest().build();
            }
            
            // 直接替换指定位置的服务
            group.getServices().set(serviceIndex, service);
            log.info("已更新分组 {} 中索引 {} 的服务: {}", group.getName(), serviceIndex, service.getName());
        } else {
            // 传统模式 (groupIndex = -1)
            if (monitoringProperties.getNetworkCheck().getServices() == null || 
                serviceIndex >= monitoringProperties.getNetworkCheck().getServices().size()) {
                return ResponseEntity.badRequest().build();
            }
            
            // 直接替换指定位置的服务
            monitoringProperties.getNetworkCheck().getServices().set(serviceIndex, service);
            log.info("已更新传统列表中索引 {} 的服务: {}", serviceIndex, service.getName());
        }
        
        // 保存到配置文件
        boolean saved = configurationFileService.saveConfiguration(monitoringProperties);
        if (!saved) {
            log.error("保存配置文件失败");
            return ResponseEntity.internalServerError().build();
        }
        
        return ResponseEntity.ok(service);
    }
} 